import React, { Component } from 'react'
import './index.css'
import PubSub from 'pubsub-js'

export default class Search extends Component {
  state = {
    users: [],
    isFirst: true, // 是否是第一次打开页面
    isLoading: false, // 是否正在加载中
    err: null, // 存储请求相关的错误信息
  }

  componentDidMount() {
    // 订阅消息
    PubSub.subscribe('atguigu', (_, stateObj) => {
      console.log(stateObj, 'stateObj')
      this.setState(stateObj)
    })
  }

  render() {
    // const {users, isFirst, isLoading, err} = this.props
    const {users, isFirst, isLoading, err} = this.state
    return (
      <div className="row">
        {
          isFirst ? <h2>欢迎使用，输入关键字，随后点击搜索</h2> :
          isLoading ? <h2>Loading...</h2> :
          err ? <h2>{err.message}</h2> :
          users.map(userObj => {
            // 函数体
            return(
              <div className="card" key={userObj.id}>
                <a href={userObj.html_url} target="_blank">
                  <img src={userObj.avatar_url} alt="head_portrait" style={{width: '100px'}} />
                </a>
                <p className="card-text">{userObj.login}</p>
              </div>
            )
          })
        }
      </div>
    )
  }
}
